/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fri.businessLayer;

import java.util.List;
import java.util.Vector;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author NguyenDongUIT
 */
public abstract class GenericDAO<T> {

    private final static String UNIT_NAME = "EJB_FRI_MODULEPU";
    @PersistenceContext(unitName = UNIT_NAME)
    protected EntityManager em;
    protected Class<T> entityClass;

    public GenericDAO(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public int save(T entity) {

        System.out.println("Save entity " + entityClass);
        int rvl = 0;
        try {
            em.persist(entity);
            rvl = 1;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return (0);
        } finally {
            //em.close();
            return rvl;
        }

    }

    public int delete(T entity) {
        System.out.println("Delete entity " + entityClass);
        int rvl = 0;
        try {
            T entityToBeRemoved = em.merge(entity);
            em.remove(entityToBeRemoved);
            rvl = 1;
        } catch (Exception e) {
            System.out.println(e.getMessage());

        } finally {
            //em.close();
            return rvl;
        }

    }

    public int update(T entity) {
        System.out.println("Update entity " + entityClass);
        
        int rvl = 0;

        try {
            em.merge(entity);
            rvl = 1;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            //em.close();
            return rvl;
        }
    }

    public T find(int entityID) {
        return em.find(entityClass, entityID);
    }

    public Vector<T> listToVector(List<T> list) {
        Vector<T> vt = null;

        if (list != null && list.size() > 0) {
            vt = new Vector<T>();
            for (T item : list) {

                vt.add(item);

            }
        }
        return vt;
    }
}
